package com.ming.sportdemo.alipay;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.ming.sportdemo.bean.Order;
import com.ming.sportdemo.service.OrderService;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AliPayController {
    @Autowired
    OrderService orderService;
    /*@GetMapping("/pay")
    public String pay(AliPay aliPay) {
        AlipayTradePagePayResponse response;
        try {
            //  发起API调用（以创建当面付收款二维码为例）
            response = Factory.Payment.Page()
                    .pay(aliPay.getSubject(), aliPay.getTraceNo(), aliPay.getTotalAmount(), "");
            System.out.println(response.toString());
            System.out.println("111111");
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return response.getBody();
    }*/
    @GetMapping("/pay")
    public String pay(int orderId) {
        Order order = orderService.getById(orderId);
        System.out.println(order);
        AlipayTradePagePayResponse response;
        try {
            //  发起API调用（以创建当面付收款二维码为例）
            response = Factory.Payment.Page()
                    .pay(String.valueOf(order.getUserId()), String.valueOf(order.getOrderId()), String.valueOf(order.getTotal()), "");
            System.out.println(response.toString());
            System.out.println("111111");
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return response.getBody();
    }


    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        System.out.println("回调函数进来");

        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                System.out.println(name + " = " + request.getParameter(name));
            }
            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String userId = request.getParameter("subject");
            String orderId = request.getParameter("out_trade_no");
            String total = request.getParameter("total_amount");
            System.out.println("userid"+userId+";orderid"+orderId+";total+"+total);
            int i = orderService.updateOrderState(Integer.parseInt(orderId));
            System.out.println(i>0?"success":"error");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 更新订单未已支付
              //  orderMapper.updateState(tradeNo, 1, gmtPayment);
                //后期加入数据库
            }
        }
        return "success";
    }

    @RequestMapping("/getUrl")
    public String getUrl(int orderId){
        String url = "http://localhost:9000/pay?orderId="+orderId;
        System.out.println(url);
        return url;
    }

}
